﻿using System;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using PoznanEvents.Helpers;

namespace PoznanEvents.Models
{
    public class Event
    {
        public int EventId { get; set; }
        public string EventTitle { get; set; }
        public string EventUrl { get; set; }
        public string EventKeywords { get; set; }
        public string EventAuthor { get; set; }
        public string EventVersion { get; set; }
        public string EventAdress { get; set; }
        public string EventCity { get; set; }
        public double EventLatitude { get; set; }
        public double EventLongitue { get; set; }
        public DateTime EventDateStart { get; set; }
        public DateTime EventDateEnd { get; set; }

        public Event(XElement eventId, XElement eventAuthor, XElement eventAddres, XElement eventDateStart, 
            XElement eventDateEnd, XElement eventUrl, XElement eventVersion, XElement eventKeyWords)
        {
            if (!String.IsNullOrEmpty(eventId.Value))
                EventId = Convert.ToInt32(eventId.Value);

            EventAuthor = eventAuthor.Value;
            EventAdress = eventAddres.Element("street").Value;

            if (!String.IsNullOrEmpty(eventAddres.Element("city").Value))
                EventCity = eventAddres.Element("street").Value;

            if (!String.IsNullOrEmpty(eventAddres.Element("lon").Value) && !String.IsNullOrEmpty(eventAddres.Element("lat").Value))
            {
                EventLatitude = StringHelper.ToDouble(eventAddres.Element("lat").Value);
                EventLongitue = StringHelper.ToDouble(eventAddres.Element("lon").Value);
            }

            EventUrl = eventUrl.Value;

            if (!String.IsNullOrEmpty(eventVersion.Value))
            {
                var html = "<html><body>";
                html += eventVersion.Value;
                html = html + "</body></html>";
                EventVersion = StringHelper.FixHtml(html);
            }

            EventVersion = eventVersion.Value;
            EventTitle = Regex.Replace(eventVersion.Value, "<.*>", " ");
            EventTitle = Regex.Replace(EventTitle, "&.*;", " ");

            if (EventTitle.Length > 50)
            {
                EventTitle = EventTitle.Substring(0, 50);
            }

            if (!String.IsNullOrEmpty(eventDateEnd.Value))
                EventDateEnd = Convert.ToDateTime(eventDateEnd.Value);
            
            if (!String.IsNullOrEmpty(eventDateStart.Value))
                EventDateStart = Convert.ToDateTime(eventDateStart.Value);
        }
    }
}
